package com.jeecg.p3.system.web.back;

import com.jeecg.p3.base.util.ComCode;
import com.jeecg.p3.base.util.JsSignUtil;
import com.jeecg.p3.base.util.WxUserInfo;
import com.jeecg.p3.base.util.WxUtils;
import com.jeecg.p3.commonweixin.entity.MyJwWebJwid;
import com.jeecg.p3.system.base.BaseController;
import com.jeecg.p3.system.entity.Course;
import com.jeecg.p3.system.entity.Product;
import com.jeecg.p3.system.order.entity.ProductDetails;
import com.jeecg.p3.system.order.service.ProductDetailsService;
import com.jeecg.p3.system.poster.entity.CustomerCoupon;
import com.jeecg.p3.system.poster.service.CustomerCouponService;
import com.jeecg.p3.system.service.CourseService;
import com.jeecg.p3.system.service.MyJwWebJwidService;
import com.jeecg.p3.system.service.ProductService;
import com.jeecg.p3.system.util.Constants;
import org.apache.velocity.VelocityContext;
import org.jeecgframework.p3.core.common.utils.AjaxJson;
import org.jeecgframework.p3.core.util.SystemTools;
import org.jeecgframework.p3.core.util.plugin.ViewVelocity;
import org.jeecgframework.p3.core.utils.common.PageQuery;
import org.jeecgframework.p3.core.utils.common.PaginatedList;
import org.jeecgframework.p3.core.utils.common.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @program: jeewx-boot-parent
 * @description: app前端接口
 * @author: binbin
 * @create: 2020-12-01 20:54
 */
@Controller
@CrossOrigin
@RequestMapping("/app/product/prop")
public class AppProductController extends BaseController {

    public Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ProductService productService;
    @Autowired
    private CourseService courseService;
    @Autowired
    private CustomerCouponService customerCouponService;
    @Autowired
    private MyJwWebJwidService myJwWebJwidService;
    @Autowired
    private ProductDetailsService productDetailsService;

    /**
     * 前端产品了列表查询
     * @param query
     * @param response
     * @param request
     * @param pageNo
     * @param pageSize
     * @return
     * @throws Exception
     */
    @RequestMapping(value="list",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public AjaxJson list(@ModelAttribute Product query, HttpServletResponse response, HttpServletRequest request,
                     @RequestParam(required = false, value = "pageNo", defaultValue = "1") int pageNo,
                     @RequestParam(required = false, value = "pageSize", defaultValue = "10") int pageSize) throws Exception{
        AjaxJson json = new AjaxJson();
        PageQuery<Product> pageQuery = new PageQuery<Product>();
        pageQuery.setPageNo(pageNo);
        pageQuery.setPageSize(pageSize);
        pageQuery.setQuery(query);
        PaginatedList paginatedList = SystemTools.convertPaginatedList(productService.queryPageList(pageQuery));
        try {
            json.setObj(paginatedList);
            json.setMsg("查询产品列表成功");
        } catch (Exception e) {
            log.info(e.getMessage());
            json.setSuccess(false);
            json.setMsg("查询产品列表失败");
        }
        return json;
    }

    /**
     * 根据商品id查询商品明细和课程信息
     * @param id
     * @param response
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value="productDetail",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public AjaxJson productDetail(@RequestParam(required = true, value = "id" ) Long id, String couponId,
                                  HttpServletResponse response,HttpServletRequest request) throws Exception{
        AjaxJson json = new AjaxJson();
        try {
            Product product = productService.queryById(id);
            List<Course> courseList = courseService.listCourseByProductId(id);
            if(StringUtils.isNotEmpty(couponId)) {
                CustomerCoupon customerCoupon = customerCouponService.findById(Long.valueOf(couponId));
                if(customerCoupon != null && StringUtils.isNotEmpty(customerCoupon.getCouponNumber())) {
                    BigDecimal price = new BigDecimal(product.getPrice());
                    BigDecimal yhMoney = new BigDecimal(customerCoupon.getCouponNumber());
                    int comResult = price.compareTo(yhMoney);
                    if(comResult != -1) {
                        product.setRealPrice(price.subtract(yhMoney).toString());
                    }
                }
            } else {
                product.setRealPrice(product.getPrice());
            }
            product.setLstCourse(courseList);
            json.setObj(product);
            json.setMsg("查询产品明细成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            json.setSuccess(false);
            json.setMsg("查询产品明细失败");
        }
        return json;
    }


    /**
     * 跳转到产品明细页面
     * @param request
     * @param response
     */
    @RequestMapping(value = "/findById",method ={RequestMethod.GET, RequestMethod.POST})
    public void toMain(HttpServletRequest request, HttpServletResponse response) {
        try {
            VelocityContext velocityContext = new VelocityContext();
            String viewName = "system/back/product.html";
            ViewVelocity.view(request, response, viewName, velocityContext);
        } catch (Exception e) {
            logger.error("跳转到产品明细页面！！！");
            e.printStackTrace();
        }
    }

    /**
     * 跳转到商品介绍界面
     * @param request
     * @param response
     */
    @RequestMapping(value = "/introduce",method ={RequestMethod.GET, RequestMethod.POST})
    public void introduce(HttpServletRequest request, HttpServletResponse response, String id,
                          String couponId) throws Exception {
        logger.info("----------introduce----start-----------");
        VelocityContext velocityContext = new VelocityContext();
        WxUserInfo wxUserInfo = getWxUserInfo(request);
        String toUrl;
        if(StringUtils.isNotEmpty(couponId)) {
            toUrl = ComCode.systemUrl + "/app/product/prop/introduce.do?id="+id+"&couponId="+couponId;
        } else {
            toUrl = ComCode.systemUrl + "/app/product/prop/introduce.do?id="+id;
        }

        if(wxUserInfo == null || StringUtils.isEmpty(wxUserInfo.getOpenid())) {
            AjaxJson j = WxUtils.getWxUserDetail(request);
            if(j.isSuccess()) {
                wxUserInfo = (WxUserInfo) j.getObj();
                request.getSession().setAttribute(Constants.wxInfo, j.getObj());
            } else {
                String url = ComCode.authorize + "appid=" + ComCode.appid + "&redirect_uri="
                        + URLEncoder.encode(toUrl, "UTF-8") + ComCode.userinfoUrl;
                response.sendRedirect(url);
                return;
            }
        }
        /*String code = request.getParameter("code");
        if(StringUtils.isNotEmpty(code)) {
            logger.info("------检测到有code进行再次跳转！！！" + code);
            logger.info("------toUrl！！！" + toUrl);
            response.sendRedirect(toUrl);
            return;
        }*/
        MyJwWebJwid myJwWebJwid = myJwWebJwidService.queryByJwid(Constants.wxid);
        String jsapi_ticket = myJwWebJwid.getJsApiTicket();
        Map<String, String> map = JsSignUtil.sign(jsapi_ticket, toUrl);
        Product product = productService.queryById(Long.valueOf(id));
        product.setBigImg(ComCode.systemUrl + product.getBigImg());
        velocityContext.put("product",product);
        velocityContext.put("wx",map);
        velocityContext.put("appId", ComCode.appid);
        String viewName = "system/back/product/productDetail.html";

        ViewVelocity.view(request, response, viewName, velocityContext);
    }


    /**
     *
     * @param request
     * @param response
     * @param id
     * @param videoId
     */
    @RequestMapping(value = "/openVideo",method ={RequestMethod.GET, RequestMethod.POST})
    public void openVideo(HttpServletRequest request, HttpServletResponse response, String id, String videoId) throws Exception {
        logger.info("----------index----start-----------");
        if(StringUtils.isEmpty(id)) {
            return;
        }
        Course course = courseService.queryById(Long.valueOf(id));
        if(course == null) {
            return;
        }
        VelocityContext velocityContext = new VelocityContext();
        WxUserInfo wxUserInfo = getWxUserInfo(request);
        String toUrl = ComCode.systemUrl + "/app/product/prop/openVideo.do?id="+id+"&videoId="+videoId;
        if(wxUserInfo == null || StringUtils.isEmpty(wxUserInfo.getOpenid())) {
            AjaxJson j = WxUtils.getWxUserDetail(request);
            if(j.isSuccess()) {
                wxUserInfo = (WxUserInfo) j.getObj();
                request.getSession().setAttribute(Constants.wxInfo, j.getObj());
            } else {
                String url = ComCode.authorize + "appid=" + ComCode.appid + "&redirect_uri="
                        + URLEncoder.encode(toUrl, "UTF-8") + ComCode.userinfoUrl;
                response.sendRedirect(url);
                return;
            }
        }
        ProductDetails param = new ProductDetails();
        param.setOpenId(wxUserInfo.getOpenid());
        param.setProductId(course.getProduct().getId().toString());
        List<ProductDetails> list = productDetailsService.findByParam(param);
        Boolean isShow = false;
        for(ProductDetails p : list) {
            if(ComCode.statusNormal.equals(p.getUseStatus().toString())) {
                isShow = true;//有支付过的有效订单
            }
        }
        //跳转到课程列表界面
        /*if(!isShow) {
            toUrl = ComCode.systemUrl + "/app/product/prop/introduce.do?id="+id+"&couponId="+couponId;
        }*/

        /*String code = request.getParameter("code");
        if(com.jeecg.p3.base.util.StringUtils.isNotEmpty(code)) {
            logger.info("------检测到有code进行再次跳转！！！");
            response.sendRedirect(toUrl);
            return;
        }*/
        //公开课处理
        if(ComCode.statusNormal.equals(course.getIsPublic()) || isShow) {
            MyJwWebJwid myJwWebJwid = myJwWebJwidService.queryByJwid(Constants.wxid);
            String jsapi_ticket = myJwWebJwid.getJsApiTicket();
            Map<String, String> map = JsSignUtil.sign(jsapi_ticket, toUrl);
            if(StringUtils.isNotEmpty(course.getVideoCoverUrl())) {
                if(!course.getVideoCoverUrl().startsWith("http")) {
                    course.setVideoCoverUrl(ComCode.systemUrl + course.getVideoCoverUrl());
                }
            }
            velocityContext.put("course",course);
            velocityContext.put("wx",map);
            velocityContext.put("appId", ComCode.appid);
            String viewName = "system/back/product/open_video.html";
            ViewVelocity.view(request, response, viewName, velocityContext);
        } else {
            return;
        }





    }

}
